package sp.service;

import sp.dao.BaseDao;
import sp.dao.ClassesDao;
import sp.dao.ClassesDaoImpl;
import sp.dao.Page;
import sp.entity.Classes;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ClassesServiceImpl implements ClassesService {
    ClassesDao classesDao = new ClassesDaoImpl();
    @Override
    public Page<Classes> findPage(String classId, String className, int page, int rows) {
        Map<String,String> params = new HashMap<>();
        if(classId !=null&&classId.trim().length()>0) params.put("classId",classId);
        if(className !=null&&className.trim().length()>0) params.put("className",className);
        return classesDao.find(params,page,rows);
    }
    public void delete(String id){
        boolean autocommit = false;
        try {
            autocommit = BaseDao.begin();
            classesDao.delete(id);
            BaseDao.commit(autocommit);
        } catch (SQLException e) {
            try {
                BaseDao.rollback(autocommit);
            } catch (SQLException ex) {
                ex.printStackTrace();
                throw  new RuntimeException(ex);
            }
        }

    }

    @Override
    public void addClass(Classes cls) {
        boolean autoCommit = false;
        try {
            autoCommit = BaseDao.begin();
            classesDao.addClass(cls);
            BaseDao.commit(autoCommit);
        } catch (SQLException e) {
            try {
                BaseDao.rollback(autoCommit);
            } catch (SQLException e1) {
                e.printStackTrace();
                throw new RuntimeException(e1);
            }
        }
    }

    @Override
    public void updateClass(Classes cls) {
        boolean autoCommit = false;
        try {
            autoCommit = BaseDao.begin();
            classesDao.updateClass(cls);
            BaseDao.commit(autoCommit);
        } catch (SQLException e) {
            try {
                BaseDao.rollback(autoCommit);
            } catch (SQLException e1) {
                e.printStackTrace();
                throw new RuntimeException(e1);
            }
        }
    }

    @Override
    public List<Classes> findAllType() {
        return classesDao.findAllType();
    }
}
